package com.wanli.agent.homepage;


import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;
import com.google.gson.Gson;
import com.wanli.agent.R;
import com.wanli.agent.base.BaseDialog;
import com.wanli.agent.base.BaseFragment;
import com.wanli.agent.base.DataCallBack;
import com.wanli.agent.bean.AgentShowBean;
import com.wanli.agent.bean.BaseResponseBean;
import com.wanli.agent.bean.DailyStatisticsBean;
import com.wanli.agent.bean.IncomeNewBean;
import com.wanli.agent.bean.IndexMessageBean;
import com.wanli.agent.bean.StoreActiveBean;
import com.wanli.agent.bean.UserInfoBean;
import com.wanli.agent.homepage.model.HomePageModelImpl;
import com.wanli.agent.homepage.model.IHomePageModel;
import com.wanli.agent.mine.model.MineModelImpl;
import com.wanli.agent.utils.DateTimeUtil;
import com.wanli.agent.utils.LogUtils;
import com.wanli.agent.utils.NumberFormatUtils;
import com.wanli.agent.utils.SPManager;
import com.wanli.agent.utils.ToastUtil;
import com.wanli.agent.widget.CommonDialog;
import com.wanli.agent.widget.CommonNoTitleDialog;
import com.wanli.agent.widget.MarqueeTextView;
import com.youth.banner.Banner;
import com.youth.banner.adapter.BannerImageAdapter;
import com.youth.banner.holder.BannerImageHolder;
import com.youth.banner.indicator.CircleIndicator;
import com.youth.banner.listener.OnBannerListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 首页
 */
public class HomePageFragment extends BaseFragment implements OnBannerListener {
    @BindView(R.id.tv_order_fee_sum)
    TextView tvOrderFeeSum;
    @BindView(R.id.tv_store_sum)
    TextView tvStoreSum;
    @BindView(R.id.ll_add_agent)
    LinearLayout llAddAgent;
    @BindView(R.id.ll_add_merchant)
    LinearLayout llAddMerchant;
    @BindView(R.id.tv_withdraw)
    LinearLayout tvWithdraw;
    @BindView(R.id.tv_marquee)
    MarqueeTextView tvMarquee;
    @BindView(R.id.ll_marquee)
    LinearLayout llMarquee;
    @BindView(R.id.tv_high_quality_sum)
    TextView tvHighQualitySum;
    @BindView(R.id.tv_new_sum)
    TextView tvNewSum;
    @BindView(R.id.tv_silence_sum)
    TextView tvSilenceSum;
    @BindView(R.id.banner)
    Banner banner;
    private IHomePageModel homePageModel;
    private CommonNoTitleDialog.Builder dialogBuild;
    private CommonDialog.Builder dialogTitleBuild;
    private IncomeNewBean incomeNewBean;
    private int channel_type;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home_page, container, false);
        ButterKnife.bind(this, view);
        initView();
        return view;
    }

    public void initView() {
        homePageModel = new HomePageModelImpl();
        requestData();
        requestMessage();
        requestStoreFilterCount();
        requestUserInfo();
        initBanner();
    }

    @Override
    public void onResume() {
        super.onResume();
        requestData();
        requestStoreFilterCount();
        requestMoneyDetailIsNew();

    }

    private boolean isViewCreated; // 界面是否已创建完成
    private boolean isVisibleToUser; // 是否对用户可见

    /**
     * Fragment 创建期间setUserVisibleHint()方法是在onActivityCreated()之前被调用
     */
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        this.isVisibleToUser = isVisibleToUser;
        tryLoadData();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        isViewCreated = true;
        tryLoadData();
    }

    public void tryLoadData() {
        if (isViewCreated && isVisibleToUser) {
            requestData();
            requestStoreFilterCount();
            requestMoneyDetailIsNew();
        }
    }

    /**
     * 用户信息
     */
    public void requestUserInfo() {
        new MineModelImpl().requestMine(new DataCallBack<UserInfoBean>() {
            @Override
            public void onSuccessful(UserInfoBean bean) {
                channel_type = bean.getData().getChannel_type();
                SPManager.getInstance().saveUserInfoJson(new Gson().toJson(bean));

                if (2==channel_type){
//                    banner.setVisibility(View.VISIBLE);
//                    createCustomDialogTwo();
                }
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    public void initBanner() {


        int iv_standard = R.drawable.iv_banner;

        List<Integer> imgList = new ArrayList<>();
        imgList.add(iv_standard);
        imgList.add(iv_standard);
        imgList.add(iv_standard);

        banner.setAdapter(new BannerImageAdapter<Integer>(imgList) {
            @Override
            public void onBindView(BannerImageHolder holder, Integer data, int position, int size) {

                Glide.with(holder.itemView)
                        .load(data)
                        .into(holder.imageView);
            }
        }).setIndicator(new CircleIndicator(getContext())).setLoopTime(3000).setOnBannerListener(this);

    }

    /**
     * 消息列表
     */
    public void requestMessage() {
        homePageModel.requestIndexMessage(1, new DataCallBack<IndexMessageBean>() {
            @Override
            public void onSuccessful(IndexMessageBean bean) {
                if (isDestroy()) {
                    return;
                }
                if (bean.getData().getItemList() != null && bean.getData().getItemList().size() > 0) {
                    tvMarquee.setText(bean.getData().getItemList().get(0).getContent());
                    tvMarquee.setMarqueeEnable(true);
                    llMarquee.setVisibility(View.VISIBLE);
                    //1新消息  0已读消息
                    if (bean.getData().getItemList().get(0).getIs_new() == 1) {
                        dialogTitleBuild = new CommonDialog.Builder(mActivity);
                        dialogTitleBuild.setTitle("新消息通知");
                        dialogTitleBuild.setMessage(bean.getData().getItemList().get(0).getContent());
                        dialogTitleBuild.setPositiveButton("我知道了", v -> {
                            requestSaveNewStatus(bean.getData().getItemList().get(0).getMessage_no());
                            dialogTitleBuild.dismiss();
                        });
                        dialogTitleBuild.setNegativeButton("取消", v -> dialogTitleBuild.dismiss());
                        dialogTitleBuild.setCancelable(false);
                        dialogTitleBuild.show();
                    }
                } else {
                    llMarquee.setVisibility(View.GONE);
                }
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    /**
     * 消息 阅读
     */
    public void requestSaveNewStatus(String message_no) {
        homePageModel.requestSaveNewStatus(message_no, new DataCallBack<BaseResponseBean>() {
            @Override
            public void onSuccessful(BaseResponseBean bean) {

            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    /**
     * 今日数据
     */
    public void requestData() {
        homePageModel.requestDailyStatistics(DateTimeUtil.getToDayDate(), new DataCallBack<DailyStatisticsBean>() {
            @Override
            public void onSuccessful(DailyStatisticsBean bean) {
                String orderFeeSum = NumberFormatUtils.formatTwoDecimal(Double.parseDouble(bean.getData().getOrder_fee_sum()) / 100);
                tvOrderFeeSum.setText(orderFeeSum);
                tvStoreSum.setText(bean.getData().getStore_sum());
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    /**
     * 门店统计
     */
    public void requestStoreFilterCount() {
        homePageModel.requestStoreFilterCount(new DataCallBack<StoreActiveBean>() {
            @Override
            public void onSuccessful(StoreActiveBean bean) {
                tvHighQualitySum.setText(bean.getData().getHigh_quality_store_count());
                tvNewSum.setText(bean.getData().getNew_store_count());
                tvSilenceSum.setText(bean.getData().getSilence_store_count());
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    /**
     * 控制收益
     */
    public void requestMoneyDetailIsNew() {
        homePageModel.requestMoneyDetailIsNew(new DataCallBack<IncomeNewBean>() {
            @Override
            public void onSuccessful(IncomeNewBean bean) {
                incomeNewBean = bean;
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }


    @OnClick({R.id.ll_high_quality_sum, R.id.ll_new_sum, R.id.ll_silence_sum, R.id.ll_add_agent, R.id.ll_add_merchant, R.id.tv_withdraw, R.id.ll_event_1, R.id.ll_event_2, R.id.ll_event_3, R.id.ll_event_4, R.id.ll_event_5, R.id.ll_event_6, R.id.ll_event_7, R.id.ll_event_8, R.id.ll_event_9, R.id.ll_today_money, R.id.ll_today_number})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_add_agent:
                skipToActivity(AddAgentActivity.class);
                break;
            case R.id.ll_add_merchant:
                skipToActivity(MerchantIntoActivity.class);
                break;
            case R.id.tv_withdraw:
                UserInfoBean userInfoBean = new Gson().fromJson(SPManager.getInstance().getUserInfoJson(), UserInfoBean.class);
                if (TextUtils.isEmpty(userInfoBean.getData().getCard_no())) {
                    dialogBuild = new CommonNoTitleDialog.Builder(mActivity);
                    dialogBuild.setMessage("请前往“结算信息”页面绑定银行卡后进行操作？");
                    dialogBuild.setPositiveButton("立即前往", v -> {
                        dialogBuild.dismiss();
                        skipToActivity(SettlementInfoActivity.class);
                    });
                    dialogBuild.setNegativeButton("取消", v -> dialogBuild.dismiss());
                    dialogBuild.setCancelable(false);
                    dialogBuild.show();
                } else {
                    skipToActivity(WithdrawActivity.class);
//                    if (incomeNewBean != null && incomeNewBean.getData().getIs_new() == 1) {
//                        skipToActivity(WithdrawNewActivity.class);
//                    } else {
//                        skipToActivity(WithdrawActivity.class);
//                    }
                }
                break;
            case R.id.ll_event_1:
                skipToActivity(AgentListActivity.class);
                break;
            case R.id.ll_event_2:
                skipToActivity(MerchantListActivity.class);
                break;
            case R.id.ll_event_3:
                skipToActivity(MachinesActivity.class);
                break;
            case R.id.ll_event_4:
                if (incomeNewBean != null && incomeNewBean.getData().getIs_new() == 1) {
                    skipToActivity(IncomeNewActivity.class);
                } else {
                    skipToActivity(IncomeActivity.class);
                }
                break;
            case R.id.ll_event_5:
                skipToActivity(TransactionQueryActivity.class);
                break;
            case R.id.ll_event_6:
                skipToActivity(HelpCenterActivity.class);
                break;
            case R.id.ll_event_7:
                skipToActivity(MessageCenterActivity.class);
                break;
            case R.id.ll_event_8:
                skipToActivity(SettlementInfoActivity.class);
                break;
            case R.id.ll_event_9:
                LogUtils.e("首页","userInfoBean：" + SPManager.getInstance().getUserInfoJson());
                if (TextUtils.isEmpty(SPManager.getInstance().getUserInfoJson())) {
                    ToastUtil.showShort("获取用户信息失败，请稍后再试！");
                } else {
                    skipToActivity(BusinessDataActivity.class);
                }
                break;
            case R.id.ll_today_money:
                skipToActivity(TransactionQueryActivity.class);
                break;
            case R.id.ll_today_number:
                skipToActivity(MerchantListActivity.class);
                break;
            case R.id.ll_high_quality_sum:
                Intent intent = new Intent(mActivity, ActiveListActivity.class);
                intent.putExtra("type", "high_quality");
                mActivity.startActivity(intent);
                break;
            case R.id.ll_new_sum:
                intent = new Intent(mActivity, ActiveListActivity.class);
                intent.putExtra("type", "new");
                mActivity.startActivity(intent);
                break;
            case R.id.ll_silence_sum:
                intent = new Intent(mActivity, ActiveListActivity.class);
                intent.putExtra("type", "silence");
                mActivity.startActivity(intent);
                break;
        }
    }

    @Override
    public void OnBannerClick(Object data, int position) {
        Log.i("tag", "你点了第"+position+"张轮播图");
    }

    /**
     * 弹框
     */

    private void createCustomDialogTwo() {

        BaseDialog baseDialog = new BaseDialog(getContext(), R.style.BaseDialog, R.layout.shop_updata_layout);

        ImageView isCoerce = baseDialog.findViewById(R.id.isCoerce);
        isCoerce.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                baseDialog.dismiss();
            }
        });
        //点击空白不消失
        baseDialog.setCanceledOnTouchOutside(true);
        //点击返回不消失
        baseDialog.setCancelable(true);
        baseDialog.show();

    }
}
